import KaseoProgram from "../KaseoProgram";
import {KaseoRuntimeBridge} from "../KaseoRuntime";
import UIPage from "./UIPage";


export default class UIApplication extends KaseoProgram {
    protected __pageStack: UIPage[] = []
    protected __pageToRender: UIPage | undefined

    protected pushPage(page: UIPage) {
        this.__pageStack.push(page)
        this.__pageToRender = page
    }

    protected popPage() {
        this.__pageStack.pop()
        
        if (this.__pageStack.length != 0)
            this.__pageToRender = this.__pageStack[this.__pageStack.length - 1]
    }

    onKnock(bridge: KaseoRuntimeBridge): void {
        const tos = this.__pageStack[this.__pageStack.length - 1]   

        tos?.onKnock(bridge)
    }

    onUpdate(bridge: KaseoRuntimeBridge): void {
        if (this.__pageToRender) {
            this.__pageToRender.onAwakeRender(bridge)
            this.__pageToRender = undefined
        }

        if (this.__pageStack.length == 0) {
            bridge.exit(this)
        }

        const tos = this.__pageStack[this.__pageStack.length - 1]

        tos.onUpdate(bridge)

        if (tos.__$$page_quit)
            this.popPage()
    }
}
